<extend name="public@base" />
<block name="seo">
    <title>推广注册</title>
    <style>
        .container {
            margin-top: 30px;
            padding: 0 20px;
        }

        .form-container {
            max-width: 400px;
            margin: 0 auto;
            margin-top: 36%;
            background-color: rgba(170, 200, 251, 1);
            padding: 30px 20px;
            border-radius: 5%;
        }

        .title-container {
            margin-bottom: 2rem;
            color: white;
            text-align: center;
            font-weight: bold;
        }

        .form-group {
            margin-bottom: 2rem;
        }

        .input-group-append {
            cursor: pointer;
        }

        .btn-disabled {
            cursor: not-allowed;
        }

        .btn-register {
            width: 200px;
        }
    </style>

    <body>
        <div class="container">
            <div class="form-container">
                <div class="title-container">Metaverse Mall 商城</div>
                <form id="registrationForm" method="post" action="{:url('/api/mall/Login/register')}">
                    <div class="form-group" hidden>
                        <label class="col-form-label">推荐人ID</label>
                        <input id="parent_id" class="form-control" value="{$parent_id}" name="parent_id" readonly>
                    </div>
                    <div class="form-group" hidden>
                        <label class="col-form-label">推荐人昵称</label>
                        <input class="form-control" value="{$parent_nick_name}" disabled>
                    </div>
                    <div class="form-group">
                        <!-- <label for="username" class="col-form-label">手机号码</label> -->
                        <input type="tel" class="form-control" id="username" placeholder="请输入手机号码" name="username">
                        <div id="phoneError" class="invalid-feedback">
                            手机号码格式不正确，请重新输入。
                        </div>
                    </div>
                    <div class="form-group">
                        <!-- <label for="code" class="col-form-label">验证码</label> -->
                        <div class="input-group">
                            <input type="text" class="form-control" id="code" placeholder="请输入验证码" name="code">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-primary" id="btnGetVerificationCode">获取验证码</button>
                            </div>
                        </div>
                        <div style="margin-top: 10px; font-size: 13px; color: white;">
                            <input type="radio" id="agree" name="agreement" value="agree" required>
                            <label for="agree">已同意</label>
                            <span onclick="showURL(1)">《用户协议》</span>和<span onclick="showURL(2)">《隐私政策》</span>
                        </div>
                    </div>
                    <div class="text-center">
                        <button type="submit" class="btn btn-primary btn-block btn-register">注册</button>
                    </div>
                </form>
            </div>
        </div>
        <!-- Bootstrap模态框 -->
        <div class="modal fade" id="urlModal" tabindex="-1" aria-labelledby="urlModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-fullscreen">
                <div class="modal-content">
                    <!-- <div class="modal-header">
                        <h5 class="modal-title" id="urlModalLabel">请仔细阅读</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div> -->
                    <div class="modal-body" id="urlContent">
                        <!-- URL内容将在此显示 -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="__TMPL__/public/assets/js/jquery-3.6.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                // 手机号码输入框失去焦点时检查合法性
                $('#username').blur(function () {
                    var phoneNumber = $(this).val();
                    if (!isValidPhoneNumber(phoneNumber)) {
                        $('#phoneError').show();
                        $(this).addClass('is-invalid');
                    } else {
                        $('#phoneError').hide();
                        $(this).removeClass('is-invalid');
                    }
                });

                // 获取验证码按钮点击事件
                $('#btnGetVerificationCode').click(function () {
                    var mobile = $('#username').val(); // 获取手机号码
                    var url = window.location.origin + '/api/mall/login/sendCode'; // 获取当前页面的域名并拼接 API 地址

                    $.ajax({
                        type: 'POST',
                        url: url,
                        contentType: 'application/json',
                        data: JSON.stringify({ mobile: mobile }),
                        success: function (response) {
                            if (response.code === 1) {
                                // 请求成功，开始倒计时
                                var timeLeft = 30;
                                $('#btnGetVerificationCode').prop('disabled', true).addClass('btn-disabled').text('重新发送(' + timeLeft + 's)');
                                var countdown = setInterval(function () {
                                    timeLeft--;
                                    if (timeLeft > 0) {
                                        $('#btnGetVerificationCode').text('重新发送(' + timeLeft + 's)');
                                    } else {
                                        clearInterval(countdown);
                                        $('#btnGetVerificationCode').prop('disabled', false).removeClass('btn-disabled').text('获取验证码');
                                    }
                                }, 1000);
                            } else {
                                // 请求失败，处理错误
                                alert('请求验证码失败:' + response.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            // 请求失败，处理错误
                            console.error('发生错误:', error);
                            alert('发生错误:' + error);
                        }
                    });
                });

                // 检查手机号码是否合法
                function isValidPhoneNumber(phoneNumber) {
                    // 这里可以编写自定义的手机号码合法性检查逻辑，例如正则表达式等
                    // 这里简单起见，假设手机号码为11位数字
                    return /^\d{11}$/.test(phoneNumber);
                }

                // 验证表单数据的合法性
                function validateForm() {
                    var parent_id = $('#parent_id').val();
                    var username = $('#username').val();
                    var code = $('#code').val();
                    if (!username || !code || !parent_id) {
                        alert('请填写完整表单！' + username + code + parent_id);
                        return false;
                    }
                    return true;
                }

                $('#registrationForm').submit(function (e) {
                    // 阻止表单默认提交行为
                    e.preventDefault();

                    var agreeChecked = document.getElementById("agree").checked;
                    if (!agreeChecked) {
                        alert("请同意用户协议！");
                        return;
                    }

                    // 验证表单数据合法性
                    if (!validateForm()) {
                        return;
                    }

                    // 获取表单数据
                    var formData = {
                        username: $('#username').val(),
                        code: $('#code').val(),
                        parent_id: $('#parent_id').val()
                    };

                    // 发送 AJAX 请求
                    $.ajax({
                        type: 'POST',
                        url: '/api/mall/login/register',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function (response) {
                            // 请求成功，处理返回的数据
                            if (response.code === 1) {
                                // 注册成功，跳转到下载页面
                                window.location.href = response.url;
                            } else {
                                // 注册失败，显示错误消息
                                alert('注册失败：' + response.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            // 请求失败，处理错误
                            console.error('注册失败:', error);
                            alert('注册失败，请稍后重试。' + error);
                        }
                    });
                });

            });
            function showURL(type) {
                console.log(type);
                var url = window.location.origin + (type == 1 ? "/agreement.html" : "/privacy.html");
                var iframe = document.createElement('iframe');
                iframe.src = url;
                iframe.style.width = '100%';
                iframe.style.height = '100%';
                iframe.style.border = 'none';
                document.getElementById("urlContent").innerHTML = ''; // 清空之前的内容
                document.getElementById("urlContent").appendChild(iframe);
                var modal = new bootstrap.Modal(document.getElementById('urlModal'), {});
                modal.show();
            }            
        </script>
    </body>
</block>